package com.example.weatherview

import android.Manifest
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.database.getStringOrNull
import androidx.loader.app.LoaderManager
import androidx.loader.app.LoaderManager.LoaderCallbacks
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import com.example.weatherview.analyze.FileAnalyzer
import com.example.weatherview.view.a1.SunView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity(), FileAnalyzer.AnalyzerListener {

    companion object{
        const val TAG = "MainActivity"
    }

    private val mP = registerForActivityResult(ActivityResultContracts.RequestPermission()){
        if (it){
            //getCount()
            //iniLoader()
            getFile()
        }
    }

    private val mG = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
        val data = it.data
        val resultCode = it.resultCode
        Log.d(TAG, "$data  $resultCode")
        getFile()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        FileAnalyzer.setListener(this)
        findViewById<SunView>(R.id.sun).setOnClickListener {
            // startActivity(Intent(this,TestActivity::class.java))
            Ping.pingAddress("google.com")
        }


        findViewById<Button>(R.id.open).setOnClickListener {
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.R){
                if (!Environment.isExternalStorageManager()) {
                    val intent =  Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.data = Uri.parse("package:" + this.packageName);
                    mG.launch(intent)
                }else{
                    getFile()
                }
            }else{
                mP.launch(Manifest.permission.READ_EXTERNAL_STORAGE )
            }



        }
    }


    private fun getFile(){
        thread {
            val start = System.currentTimeMillis()
            val externalStorageDirectory = Environment.getExternalStorageDirectory()
            Log.d(TAG, "Environment:${externalStorageDirectory.path}")
            GlobalScope.launch(Dispatchers.IO) {
                FileAnalyzer.start(externalStorageDirectory)
                Log.d(TAG, "end time ${System.currentTimeMillis()-start}")
            }
        }
    }
    private fun getCount() {
        val contentResolver = contentResolver

        //val contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        //val contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        val contentUri = MediaStore.Files.getContentUri("external")

        val query = contentResolver.query(contentUri, null, null, null, null)

        query?.let {
            val columnNames = query.getColumnNames()
            columnNames?.forEach {
                Log.d(TAG, "getCount: $it")
            }
            while (query.moveToNext()) {
                columnNames?.forEach {

                }
                val columnIndex = query.getColumnIndex("mime_type")
                val string = query.getString(columnIndex)
                //Log.d(TAG, "$it:$string")
                Log.d(TAG, "$it:$string")
                Log.d(TAG, "=====================")
            }
        }
        query?.close()
    }


    private fun scanOtherFiles(directory: File) {
        val files = directory.listFiles()
        if (files != null) {
            for (file in files) {
                if (file.isDirectory) {
                    // 递归调用以处理子目录
                    scanOtherFiles(file)
                } else {
//                    if (file.name.contains(".mp4")) {
//                        Log.d(TAG, "Other File: name:${file.name} size:${file.length()}  path:${file.absolutePath} ")
//                    }
                    // 处理其他文件
                    Log.d(TAG, "Other File: name:${file.name} size:${file.length()}  path:${file.absolutePath} ")
                }
            }
        }
    }

    private fun iniLoader() {
        val contentUri = MediaStore.Files.getContentUri("external")
        val instance = LoaderManager.getInstance(this)
        instance.initLoader(1,null,object :LoaderCallbacks<Cursor>{
            override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
                val uri = MediaStore.Files.getContentUri(MediaStore.VOLUME_INTERNAL)
                return CursorLoader(this@MainActivity,contentUri,null,null,null,null)
            }

            override fun onLoaderReset(loader: Loader<Cursor>) {

            }

            override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
                if (loader.id==1 && data!=null) {
                    while (data.moveToNext()) {
                        val SIZE = data.getColumnIndex(MediaStore.Files.FileColumns.SIZE)
                        val DISPLAY_NAME = data.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME)
                        val MIME_TYPE = data.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE)
                        val size = data.getInt(SIZE)
                        val type = data.getStringOrNull(MIME_TYPE)
                        val len =0
                        if (size>=len && type!=null){
                            val name = data.getString(DISPLAY_NAME)
                            Log.d(TAG, "onLoadFinished: size:$size  name:$name  type:$type")
                        }
                    }
                    data.close()
                    Log.d(TAG, "onLoadFinished: end")
                }
            }

        })

    }

    override fun onAnalyzer(file: File) {
        Log.d(TAG, "onAnalyzer: ${file.name}  ${file.absolutePath}")
    }

    override fun onFinish(files: List<File>) {
        Log.d(TAG, "onFinish: ${files.size}")
    }
}